<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>机构名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.groupName"
                        clearable
                        placeholder="机构名称"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                    >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                    >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-plus"
                @click="clickAdd('添加规则', loadGroupIndustry)"
                >添加规则
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                default-expand-all
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                    prop="groupName"
                    label="机构名称"
                    min-width="80"
                    align="center"
                >
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="任务名称"
                    min-width="80"
                    align="center"
                >
                </el-table-column>
                <el-table-column
                    prop="timeType"
                    label="任务类型"
                    min-width="80"
                    align="center"
                >
                    <template slot-scope="scope">
                        <k-tag
                            :tag="groupLogRuleTimeType[scope.row.timeType]"
                        ></k-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="sourceTypes"
                    label="资源类别"
                    min-width="80"
                    align="center"
                >
                    <template slot-scope="scope">
                        <k-tag
                            v-for="(item, index) in scope.row.sourceTypes"
                            :key="index"
                            :tag="userLogSourceType[item]"
                            text
                            style="display: block;"
                        ></k-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="时间模式" width="100">
                    <template slot-scope="scope">
                        <k-tag
                            :tag="timeModes[scope.row.timeMode]"
                            text
                        ></k-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="start"
                    label="开始时间"
                    min-width="80"
                ></el-table-column>
                <el-table-column
                    prop="end"
                    label="结束时间"
                    min-width="80"
                ></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template slot-scope="scope">
                        <k-tag :tag="ruleStatus[scope.row.status]" text></k-tag>
                    </template>
                </el-table-column>

                <el-table-column
                    prop="createdTime"
                    label="创建时间"
                    min-width="80"
                ></el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    width="250"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            v-if="
                                !scope.row.edit &&
                                    scope.row.timeType === 'future'
                            "
                            lass="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="
                                clickSimpleEdit(scope.row, '规则信息', editCall)
                            "
                            >编辑
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            type="text"
                            size="mini"
                            class="danger"
                            icon="el-icon-delete"
                            :loading="scope.row.opLoading"
                            @click="
                                tableDelete(
                                    '/user/sys/group/log/rule/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true
                                )
                            "
                            >删除
                        </el-button>
                        <el-button
                            v-if="
                                (scope.row.timeType === 'future' &&
                                    scope.row.status === 2) ||
                                    scope.row.status === 5
                            "
                            type="text"
                            size="mini"
                            class="danger"
                            :icon="
                                scope.row.status === 2
                                    ? 'el-icon-video-pause'
                                    : 'el-icon-video-play'
                            "
                            :loading="scope.row.opLoading"
                            @click="stopRule(scope.row)"
                            >{{ scope.row.status === 2 ? "暂停" : "继续" }}
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            lass="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="toDetail(scope.row)"
                            >明细
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            :before-close="dialogClose"
            custom-class="two-dialog"
            width="1000px !important"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="12em"
                :rules="dataFormRule"
            >
                <div class="row">
                    <el-form-item label="注水名称" prop="name">
                        <el-input v-model="dataForm.name"></el-input>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="所属机构" prop="groupId">
                        <el-select
                            v-model="dataForm.groupId"
                            placeholder="选择机构"
                            filterable
                            remote
                            reserve-keyword
                            :remote-method="loadGroups"
                            :loading="flag.loadGroupLoading"
                            :disabled="!dataForm.addAction"
                        >
                            <el-option
                                v-for="item in groups"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="作用平台" prop="sourceTypes">
                        <el-select
                            v-model="dataForm.sourceTypes"
                            size="small"
                            placeholder="数据类型"
                            multiple
                            clearable
                        >
                            <el-option
                                v-for="item in sourceTypes"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item label="时间类型" prop="timeType">
                        <el-radio-group
                            v-model="dataForm.timeType"
                            :disabled="!dataForm.addAction"
                            @change="timeTypeChange"
                        >
                            <el-radio label="future">预约未来</el-radio>
                            <el-radio label="pastRandom">修改过往</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
                <div class="row">
                    <el-form-item prop="start" label="时间范围">
                        <el-date-picker
                            v-if="
                                dataForm.timeType === 'future' &&
                                    dataForm.timeMode < 3
                            "
                            v-model="times"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd HH:mm:ss"
                        >
                        </el-date-picker>
                        <el-time-picker
                            v-else-if="dataForm.timeType === 'future'"
                            v-model="times"
                            is-range
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            placeholder="选择时间范围"
                            value-format="HH:mm:ss"
                        >
                        </el-time-picker>
                        <el-date-picker
                            v-else
                            v-model="times"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd"
                        >
                        </el-date-picker>
                    </el-form-item>
                </div>
                <el-divider></el-divider>
                <el-form-item label="日志类型">
                    <el-checkbox-group v-model="ruleLogTypes">
                        <el-checkbox
                            v-for="item in logTypes"
                            :key="item.value"
                            :label="item.value"
                            :disabled="item.disabled"
                            >{{ item.name }}</el-checkbox
                        >
                    </el-checkbox-group>
                </el-form-item>
                <el-divider></el-divider>
                <div
                    v-if="dataForm.timeType === 'future'"
                    class="rule-container"
                >
                    <el-form-item
                        v-for="type in ruleLogTypes"
                        :key="type"
                        :label="logTypes.find(v => v.value === type).name"
                    >
                        <div class="yx-start al-start">
                            <el-radio-group v-model="ruleData[type].ta">
                                <el-radio-button :label="0"
                                    >通用</el-radio-button
                                >
                                <el-radio-button :label="1"
                                    >部分行业</el-radio-button
                                >
                            </el-radio-group>
                            <div
                                v-if="
                                    ruleData[type].ta !== 2 &&
                                        ruleData[type].all
                                "
                                class="row rule-line"
                            >
                                <p class="no-wrap">通用</p>
                                <el-form-item label="注水模式" class="no-wrap">
                                    <el-radio
                                        v-model="ruleData[type].all.type"
                                        :label="0"
                                        >倍数</el-radio
                                    >
                                    <el-radio
                                        v-model="ruleData[type].all.type"
                                        :label="1"
                                        >固定值</el-radio
                                    >
                                </el-form-item>
                                <el-form-item label="">
                                    <el-input
                                        v-model="ruleData[type].all.val"
                                    ></el-input>
                                </el-form-item>
                            </div>
                            <div
                                v-if="
                                    ruleData[type].ta !== 0 &&
                                        ruleData[type].all
                                "
                            >
                                <div
                                    v-for="industry in groupIndustry"
                                    :key="industry.id"
                                    class="xy-start rule-line"
                                >
                                    <p class="no-wrap">{{ industry.name }}</p>
                                    <el-form-item
                                        label="注水模式"
                                        class="no-wrap"
                                    >
                                        <el-radio
                                            v-model="
                                                ruleData[type][industry.id].type
                                            "
                                            :label="0"
                                            >倍数</el-radio
                                        >
                                        <el-radio
                                            v-model="
                                                ruleData[type][industry.id].type
                                            "
                                            :label="1"
                                            >固定值</el-radio
                                        >
                                    </el-form-item>
                                    <el-form-item label="">
                                        <el-input
                                            v-model="
                                                ruleData[type][industry.id].val
                                            "
                                        ></el-input>
                                    </el-form-item>
                                </div>
                            </div>
                        </div>
                        <el-divider></el-divider>
                    </el-form-item>
                </div>
                <div
                    v-if="dataForm.timeType && dataForm.timeType !== 'future'"
                    class="rule-container"
                >
                    <el-form-item
                        v-for="type in logTypes.filter(v =>
                            ruleLogTypes.includes(v.value)
                        )"
                        :key="type.value"
                        :label="type.name"
                    >
                        <div class="yx-start al-start">
                            <div v-if="!type.ind" class="row rule-line">
                                <p class="no-wrap">全部</p>
                                <el-form-item label="注水模式" class="no-wrap">
                                    <el-radio
                                        v-model="ruleData[type.value].all.type"
                                        :label="0"
                                        :disabled="
                                            dataForm.timeType === 'pastRandom'
                                        "
                                        >倍数</el-radio
                                    >
                                    <el-radio
                                        v-model="ruleData[type.value].all.type"
                                        :label="1"
                                        >固定值</el-radio
                                    >
                                </el-form-item>
                                <el-form-item label="值（倍数 固定值）">
                                    <el-input
                                        v-model="ruleData[type.value].all.val"
                                    ></el-input>
                                </el-form-item>
                            </div>
                            <div v-if="type.ind">
                                <div
                                    v-for="industry in groupIndustry"
                                    :key="industry.id"
                                    class="xy-start rule-line"
                                >
                                    <p class="no-wrap">{{ industry.name }}</p>
                                    <el-form-item
                                        label="注水模式"
                                        class="no-wrap"
                                    >
                                        <el-radio
                                            v-model="
                                                ruleData[type.value][
                                                    industry.id
                                                ].type
                                            "
                                            :disabled="
                                                dataForm.timeType ===
                                                    'pastRandom'
                                            "
                                            :label="0"
                                            >倍数</el-radio
                                        >
                                        <el-radio
                                            v-model="
                                                ruleData[type.value][
                                                    industry.id
                                                ].type
                                            "
                                            :label="1"
                                            >固定值</el-radio
                                        >
                                    </el-form-item>
                                    <el-form-item label="值（倍数 固定值）">
                                        <el-input
                                            v-model="
                                                ruleData[type.value][
                                                    industry.id
                                                ].val
                                            "
                                        ></el-input>
                                    </el-form-item>
                                </div>
                            </div>
                        </div>
                        <el-divider></el-divider>
                    </el-form-item>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                    >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="
                        formDataSave(
                            '/user/sys/group/log/rule/update',
                            dataCover
                        )
                    "
                    >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { TablePage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import { get, put } from "@/api/request";
import groupRuleDetail from "@/views/models/vrs/group/groupLogRuleData";
import { sourceType } from "./groupLog.js";
export default {
    name: "GroupLogRule",
    components: { groupRuleDetail },
    mixins: [TablePage],
    data() {
        return {
            queryData: {
                groupName: null,
                haveGroupName: true
            },
            groups: [],
            groupUsers: [],
            initAddForm: {
                id: null,
                groupId: null,
                name: null,
                timeType: null,
                userIds: null,
                ips: null,
                sourceTypes: null,
                rule: null,
                timeMode: 0,
                start: null,
                end: null
            },
            flag: {
                loadGroupLoading: false
            },
            sourceTypes: sourceType,
            times: null,
            groupIndustry: null,
            ruleLogTypes: [
                "accessLog",
                "useLog",
                "paperUseLog",
                "questionUseLog",
                "timeUseLog",
                "downloadLog"
            ],
            ruleData: {
                accessLog: {
                    // 0 全部 1部分 2行业
                    ta: 0
                },
                useLog: {
                    ta: 0
                },
                paperUseLog: {
                    ta: 0
                },
                questionUseLog: {
                    ta: 0
                },
                timeUseLog: {
                    ta: 0
                },
                downloadLog: {
                    ta: 0
                }
            }
        };
    },
    computed: {
        ...mapState({
            groupLogRuleTimeType: state => state.status.groupLogRuleTimeType
        }),
        dataFormRule() {
            return {
                groupId: [
                    {
                        required: true,
                        message: "请选择机构",
                        trigger: "change"
                    }
                ],
                timeType: [
                    {
                        required: true,
                        message: "选择时间类型",
                        trigger: "change"
                    }
                ],
                sourceTypes: [
                    {
                        required: true,
                        message: "选择数据类型",
                        trigger: "change"
                    }
                ],
                start: [
                    {
                        required: true,
                        message: "清选择开始时间",
                        trigger: "change"
                    }
                ],
                end: [
                    {
                        required: true,
                        message: "清选择结束时间",
                        trigger: "change"
                    }
                ],
                rule: [
                    {
                        required: true,
                        message: "请填写规则",
                        trigger: "blur"
                    }
                ]
            };
        },
        userLogSourceType() {
            var res = {};
            sourceType.forEach(v => (res[v.value] = v.label));
            return res;
        },
        ruleStatus() {
            return {
                1: "等待运行",
                2: "运行中",
                3: "已完成",
                4: "已取消",
                5: "暂停中"
            };
        },
        timeModes() {
            return {
                0: "时间段",
                1: "每年内",
                2: "每月内",
                3: "每天内",
                4: "每时内",
                5: "每分内"
            };
        },
        logTypes() {
            return [
                {
                    value: "accessLog",
                    name: "访问量统计",
                    ind: false
                },
                {
                    value: "useLog",
                    name: "使用人次统计",
                    ind: false
                },
                {
                    value: "paperUseLog",
                    name: "试卷使用量统计",
                    ind: true
                },

                {
                    value: "questionUseLog",
                    name: "试题使用量统计",
                    ind: true
                },
                {
                    value: "timeUseLog",
                    name: "使用时长统计",
                    ind: false
                },
                {
                    value: "downloadLog",
                    name: "下载次数统计",
                    ind: false
                },
                {
                    value: "registerLog",
                    name: "注册数统计",
                    disabled: true,
                    ind: false
                }
            ];
        }
    },
    watch: {
        times(times) {
            if (times) {
                this.dataForm.start = times[0];
                this.dataForm.end = times[1];
            } else {
                this.dataForm.start = null;
                this.dataForm.end = null;
            }
        }
    },
    created() {
        this.loadGroups();
    },
    mounted() {},
    methods: {
        search(queryData) {
            this.loadTable("/user/sys/group/log/rule/page", queryData, true);
        },
        toDetail(row) {},
        loadGroups(name) {
            this.flagPromise(
                get("/user/sys/group/list", { size: 100, name }).then(
                    res => (this.groups = res)
                ),
                "loadGroupLoading"
            );
        },
        stopRule(row) {
            return this.itemEdit(
                row,
                put("/user/sys/group/log/rule/change-status", {
                    id: row.id,
                    stop: row.status === 2
                })
            ).then(() => {
                row.status = row.status === 2 ? 5 : 2;
            });
        },
        loadUser(keyword) {
            this.flagPromise(
                get("/user/cu/member/admin-page", {
                    groupId: this.dataForm.groupId,
                    keyword: keyword
                }).then(res => (this.groupUsers = res.records)),
                "loadUser"
            );
        },
        timeTypeChange() {
            this.dataForm.timeMode = 0;
            this.times = null;
            this.dataForm.userIds = null;
            this.dataForm.ips = null;
            this.logTypes.forEach(v => {
                if (this.ruleData[v.value]) {
                    this.ruleData[v.value].ta = 0;
                    Object.keys(this.ruleData[v.value]).forEach(k => {
                        if (k === "ta") return;
                        this.ruleData[v.value][k].type = 1;
                    });
                }
            });
        },
        dataCover(data) {
            data.rule = {};
            this.ruleLogTypes.forEach(type => {
                let result = {};
                Object.keys(this.ruleData[type])
                    .filter(k => k !== "ta")
                    .forEach(ind => {
                        let b = this.ruleData[type][ind].type;
                        let v = this.ruleData[type][ind].val;
                        // eslint-disable-next-line eqeqeq
                        if (v == 0) return;
                        result[ind] = `${b}_${v}`;
                    });
                if (Object.keys(result).length === 0) return;
                data.rule[type] = result;
            });
            return data;
        },
        async loadGroupIndustry() {
            if (!this.groupIndustry) {
                await get("/exam/industry/list", {
                    haveIndustryName: true
                }).then(v => {
                    this.groupIndustry = v;
                });
            }
            // 生成数据
            let keys = Object.keys(this.ruleData);
            for (let k of keys) {
                let da = this.ruleData[k];
                this.$set(da, "all", {
                    type: 1,
                    val: 0
                });
                for (let ind of this.groupIndustry) {
                    this.$set(da, ind.id, {
                        type: 1,
                        val: 0
                    });
                }
            }
        },
        async editCall(data) {
            await this.loadGroupIndustry();
            let { rule } = data;
            if (!rule) return;
            let types = Object.keys(rule);
            this.ruleLogTypes = [...types];
            for (let type of types) {
                let industryData = rule[type];
                let indIds = Object.keys(industryData);
                if (!indIds) {
                    this.ruleData[type].ta = 0;
                    continue;
                }
                if (indIds.length === 1 && indIds[0] === "all") {
                    this.ruleData[type].ta = 0;
                } else if (indIds.includes("all")) {
                    this.ruleData[type].ta = 1;
                } else {
                    this.ruleData[type].ta = 2;
                }
                for (let ind of indIds) {
                    let value = rule[type][ind];
                    let l = value.split("_");
                    this.ruleData[type][ind].type = parseInt(l[0]);
                    this.ruleData[type][ind].val = parseFloat(l[1]);
                }
            }
            this.times = [data.start, data.end];
        }
    }
};
</script>

<style lang="scss" scoped>
.rule-container {
    .rule-line {
        > p {
            width: 4em;
            text-align: right;
        }
    }
}
</style>
